package com.qf.myrbac.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.myrbac.sys.entity.SysUser;
import com.qf.myrbac.sys.service.SysMenuService;
import com.qf.myrbac.sys.service.SysUserService;
import com.qf.myrbac.utils.Constants;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Set;

public class CustomRealm extends AuthorizingRealm {
    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysMenuService menuService;

    /**
     * 获取角色信息
     *
     * @param principals the primary identifying principals of the AuthorizationInfo that should be retrieved.
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        SysUser user = (SysUser) principals.getPrimaryPrincipal();
        if (user.getUserId().equals(Constants.SUPER_ADMIN_ID)) {
            Set<String> permSet = menuService.queryAdminPermSet();
            simpleAuthorizationInfo.addStringPermissions(permSet);
        } else {
            List<String> permsListNoRepeat = menuService.queryPermList(user.getUserId());
            simpleAuthorizationInfo.addStringPermissions(permsListNoRepeat);
        }
        return simpleAuthorizationInfo;
    }

    /**
     * 获取权限信息
     *
     * @param token the authentication token containing the user's principal and credentials.
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        SysUser user = checkUsernameExist(username);
        if (user == null) {
            throw new UnknownAccountException();
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), this.getName());
        return authenticationInfo;
    }

    private SysUser checkUsernameExist(String username) {
        QueryWrapper<SysUser> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username);
        SysUser user = sysUserService.getOne(userQueryWrapper);
        return user;
    }
}
